package com.cx.web.exception;

import com.alibaba.fastjson.JSON;
import com.cx.meta.exception.ErrorResponse;
import com.cx.meta.model.vo.PageData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author flysand
 * @package com.cx.web.exception
 * @date 2021-11-12 02:07
 * @des CxResponseBodyAdvice: 设置统一的responseBody  需单独处理string  因为string可能是个view
 */
@ControllerAdvice
public class CxResponseBodyAdvice implements ResponseBodyAdvice {

    private final static Logger logger = LoggerFactory.getLogger(CxResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        logger.debug("返回信息：" + JSON.toJSONString(body));
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setData(body);

        // String无法正常返回 需单独处理成字符串
        if (body instanceof String) {
            return JSON.toJSONString(errorResponse);
        }
        if (body instanceof PageData) {
            return body;
        }
        return errorResponse;
    }
}
